package com.scst.service.impl;

import com.scst.context.BaseContext;
import com.scst.dto.ShoppingCartDTO;
import com.scst.entity.Dish;
import com.scst.entity.Setmeal;
import com.scst.entity.ShoppingCart;
import com.scst.mapper.DishMapper;
import com.scst.mapper.SetmealDishMapper;
import com.scst.mapper.SetmealMapper;
import com.scst.mapper.ShoppingCartMapper;
import com.scst.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    DishMapper dishMapper;
    @Autowired
    SetmealMapper setmealMapper;
    @Override
    public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        //判断购物车中商品是否已经存在
        ShoppingCart shoppingCart=new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        Long userId= BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);
        List<ShoppingCart > list=shoppingCartMapper.list(shoppingCart);
        //如果已经存在，只需将数量加一
        if(list!=null && list.size() >0) {
            ShoppingCart cart =list.get(0);
            cart.setNumber(cart .getNumber()+1);
            shoppingCartMapper.updateNumberById(cart);
        }else {
            //如果不存在，则需要加入一条插入语句
            //判断本次添加到购物车的是菜品还是套餐
            Long dishId=shoppingCartDTO.getDishId();
            if(dishId !=null) {
                Dish dish=dishMapper.getById(dishId);
                shoppingCart .setName(dish.getName());
                shoppingCart .setImage(dish.getImage());
                shoppingCart .setAmount(dish.getPrice() );
            }else{
                Long setmealId=shoppingCartDTO.getSetmealId();
                Setmeal setmeal =setmealMapper.getById(setmealId);
                 shoppingCart.setName(setmeal.getName());
                 shoppingCart.setImage(setmeal.getImage());
                 shoppingCart.setAmount(setmeal.getPrice());
            }
             shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        }

    }

    @Override
    public List<ShoppingCart> showShoppingCart() {
        Long userId=BaseContext.getCurrentId();
        ShoppingCart shoppingCart= ShoppingCart.builder()
                .userId(userId)
                .build();
        List<ShoppingCart> list=shoppingCartMapper.list(shoppingCart);

        return list;
    }

    @Override
    public void clean() {
        Long userId=BaseContext.getCurrentId();
        shoppingCartMapper.delete(userId);
    }
}
